from django.shortcuts import render
from django.views import View
from apps.areas.models import Area
from django import http
from django.core.cache import cache
# Create your views here.

class ProvinceAreasView(View):
    """省市区"""
    def get(self, request):
        """提供省市区数据
        1.查询省级数据
        2.序列化省级数据
        3.响应省级数据
        4.补充缓存逻辑
        """
        # 读取缓存
        province_dict_list = cache.get('province_list')

        #判断是否存在缓存
        if province_dict_list:
            return http.JsonResponse({'code': 0,
                                      'errmsg': 'ok',
                                      'province_list': province_dict_list})

        province_model_list = Area.objects.filter(parent=None)

        #查询集模型转字典列表
        province_dict_list = []
        for i in province_model_list:
            province_dict = {
                "id": i.id,
                "name":i.name
            }

            province_dict_list.append(province_dict)

        #设置缓存
        cache.set('province_list', province_dict_list, 3600)

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'province_list': province_dict_list})


class SubAreasView(View):
    """子级地区：市和区县"""
    def get(self, request, parent_id):
        """
        查询城市或区县
        :param request:
        :param parent_id: 省份id,城市id
        :return: 城市数据,区县数据
        """
        #读取缓存
        sub_data = cache.get('sub_data_%s' % parent_id)

        # 判断缓存
        if sub_data:
            return http.JsonResponse({'code': 0,
                                      'errmsg': 'ok',
                                      'sub_data': sub_data})

        #查询当前父级地区: 省份或城市
        parent_area = Area.objects.get(id=parent_id)

        #查询当前地区的子级(一查多):省份差城市, 城市差区县
        sub_model_list = parent_area.subs.all()

        #子级数据转字典列表
        sub_dict_list= []
        for i in sub_model_list:
            sub_dict = {
                'id': i.id,
                'name': i.name,
            }
            sub_dict_list.append(sub_dict)

        #子级数据
        sub_data = {
            'id': parent_area.id,   #父级id
            'name': parent_area.name,   #父级name
            'subs': sub_dict_list,  #子级字典列表
        }

        #设置子级缓存 key需要判断是省份差城市还是城市差区县选择parent_id
        cache.set('sub_data_%s' % parent_id, sub_data, 3600)

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'sub_data': sub_data})

